// 接收一个玩游戏的指令
import fs from "fs"
import { clearInterval } from "timers"
import GuessNumber from "./guessNumber.js"
import StringPuzzle from "./stringPuzzle.js"
const gameListConfig = {
    "1":GuessNumber,
    "2":StringPuzzle
}
import {setSchedule,removeSchedule} from '../schedule/index.js'
export const initGame = async (room, gameId,contact) => {
    console.log('收到指令，发起游戏开始')
    // 查找当前房间是否有游戏进行
    // const playing = await checkGameStatus(room)
    const playing = room.gameInfo
    if (playing) {
        room.say`${contact} ${playing.gameNames} 正在进行中,先结束一下吧!`
        return
        // 游戏进行中
    }
    startGames(room,gameId,contact)
}
// 检测游戏是否进行
export const checkGameStatus = (room) => {
    return new Promise((resolve, roject) => {
        try {
            let status = false
            let startingList = JSON.parse(fs.readFileSync("./dataBase/gameStatus.json"))
            let name = null
            let gameInfo = null
            startingList.map(item => {
                if (item.roomId === room.id) {
                    console.log(item)
                    status = true
                    name = item.gameNames
                    gameInfo = item
                }
            })
            console.log(name)
            resolve({ status, name: name || null, gameInfo, startingList })
        } catch (e) {
            roject(e)
        }
    })
}

const startGames = async (room, gameId,contact) => {
    let gameInfo = {
        roomId: room.id,
        gameNames: "",
        gameId: '',
        id: ''
    }
    const { game, gameList } = await getGame(gameId)
    gameInfo.gameNames = game.name
    gameInfo.gameId = game.id
    gameInfo.id = room.id + '-' + game.id
    gameInfo.rules = game.rules

    room.game =  new (gameListConfig[gameId])(gameInfo,room,contact)
    let totaTime = 0
    // 添加一个定时任务 监听当前游戏状态
    setSchedule(room.id,  '*/1 * * * * *', (v) => {
        totaTime++
        if((totaTime>=(60*60) ) || room.game.time==10){
            endGame(room)
        }
        console.log(`\n\n总时长:${totaTime}`)
        // 到时间需要执行的方法
      });

    // let startingList = JSON.parse(fs.readFileSync("./dataBase/gameStatus.json"))
// 
    // startingList.push(gameInfo)

    // fs.writeFileSync('./dataBase/gameStatus.json', JSON.stringify(startingList), 'utf8', (err) => {
    //     if (err) throw err;
    // });
        // room.gameInfo = gameInfo
    // 搞完存储状态 开始游戏
        // new gameListConfig[gameId](room.gameInfo)
    
}
// 获取当前游戏信息
const getGame = (id) => {
    return new Promise((resolve, roject) => {
        const gameList = JSON.parse(fs.readFileSync('./dataBase/game.json'))
        if (gameList.length) {
            const game = gameList.find(it => it.id == id)
            console.log(game)
            resolve({ game, gameList })
        } else {
            resolve({})
        }

    })
}
//

export const getGameResult = async (content,room,contact)=>{
    const stopGameContent = ['不玩了','停止游戏','结束游戏']
    console.log(content)
    const stop = stopGameContent.some(it=>content.indexOf(it)>-1)
    console.log(stop)
    if(room.game && content){
        if(stop){
            endGame(room,contact)
            return
        }
        if(/游戏规则/.test(content)){
            room.game.sendRules(contact)
            return
        }
        room.game.checkGuess(content,contact)
    }
}

// 结束游戏 
export const endGame = async (room) => {
    // const playList = await readFiles('./dataBase/gameStatus.json')
    let gameNames = null

    // playList.map((it, index) => {
    //     if (it.roomId == room.id) {
    //         playList.splice(index, 1)
    //         gameNames = it.gameNames
    //     }
    // })
        // await writeFiles('./dataBase/gameStatus.json',playList)
        if( room.game){
            room.game.stopGame()
            removeSchedule(room.id)
            gameNames=room.game.gameInfo.gameNames
        }
        console.log('游戏即将结束')
        delete room.game
        gameNames  ? room.say (`${gameNames} 已结束，下次想玩请@我说 "${gameNames}"`) : room.say (`没有游戏进行，想玩什么游戏的话试着@我说游戏名称`)
        console.log(room)
    }